package com.topInterview;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/19 18:38
 */
public class Leecode42_water {
    public int trap(int[] height) {
        if (height == null || height.length < 3) {
            return 0;
        }
        int N = height.length;
        int left = 0;
        int right = N - 1;
        int res = 0;


        int leftMax = height[0];
        int rightMax = height[N - 1];

        while (left <= right) {
            if (rightMax < leftMax) {
                res+=Math.max(rightMax - height[right] ,0);
                rightMax = Math.max(rightMax, height[right--]);
            } else {
                res+=Math.max(leftMax - height[left] ,0);
                leftMax = Math.max(leftMax, height[left++]);
            }
        }
        return res;
    }
}
